/*
 * @: 防抖+接力
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-10-15 14:35:11
 * @LastEditors: ziwei
 * @LastEditTime: 2021-10-15 15:13:13
 */
//debounce 先开一个定时器 只要一直点击 到时间什么都不做 就再开一个定时器
function debounce(fun,wait,opts={}) {
  let maxWait;
  if('maxWait' in opts){
    maxWait = opts.maxWait
  }
  let leading = true;//第一次点击时触发
  let trailing = true;//最后一次也要触发
  //loadash 定时器实现的
  let lastCallTime;//最后调用的时间 previous
  let timeout;
  let lastThis;//返回函数的this
  let lastArgs;//返回函数的参数

  let lastInvokeTime;
  //shouldInvoke 是否应该调用
  let shouldInvoke = function (now) {
    let sinceLastTime = now - lastCallTime;
    let sinceLastInvoke = now - lastInvokeTime;
    //true 第一次
    return lastCallTime === undefined || sinceLastTime > wait ||sinceLastInvoke>=wait
  }
  //leadingEdge 是否第一次执行
  let invokeFunc = function (time) {
    lastInvokeTime = time
    fun.apply(lastThis,lastArgs)
  }
  //startTimer就是开启一个定时器
  let startTimer = function (timeExpierd,wait) {
    timeout = setTimeout(timeExpierd,wait)
  }
  let remainingWait = function (now) {
    return wait - (now - lastCallTime)
  }
  let trailingEdge = function () {
    timeout = undefined
    if(trailing){
      invokeFunc(time)
    }
  }
  let timeExpired = function () {
    let now = Dae.now();
    if(shouldInvoke(now)){//
      //触发结束的方法
      return trailingEdge(now);
    }
    startTimer(timeExpired,remainingWait(now))
  }
  let leadingEdge = function (time) {
    if(leading){//需要执行就调用函数
      invokeFunc(time)
    }
    startTimer(timeExpierd,wait);//开启一个定时器，看下一次定时器到了，是够需要执行
  }
  let debounced = function(){
    lastThis = this;
    lastArgs  =args;
    let now = Date.now();
    //判断当前的debounce是够需要执行
    let isInvoking = shouldInvoke(now)
    lastCallTime = now;
    if(isInvoking){
      if(timeout==undefined){
        leadingEdge(now);
      }
    }
  }
  return debounced
}


function throttle(func,wait) {
  return debounce(func,wait,{
    maxWait:true
  })
}